package com.gnerv.cms.service.impl;

import com.gnerv.cms.common.CommonString;
import com.gnerv.cms.dto.TaskSaveDTO;
import com.gnerv.cms.job.DefaultJob;
import com.gnerv.cms.service.IJobDetailService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class JobDetailServiceImpl implements IJobDetailService {

    @Resource
    Scheduler scheduler;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public JobDetail createJobDetail(TaskSaveDTO taskSaveDTO) {
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put(CommonString.TASK_DATA_MAP_KEY, taskSaveDTO.toString());
        JobDetail jobDetail = JobBuilder.newJob(DefaultJob.class)
                .withIdentity(taskSaveDTO.getUkId(), CommonString.TASK_GROUP_NAME)
                .setJobData(jobDataMap)
                .storeDurably()
                .build();
        return jobDetail;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public JobDetail createJobDetail(TaskSaveDTO task, Class<? extends Job> clazz) {
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put(CommonString.TASK_DATA_MAP_KEY, task.toString());
        JobDetail jobDetail = JobBuilder.newJob(clazz)
                .withIdentity(task.getUkId(), CommonString.TASK_GROUP_NAME)
                .setJobData(jobDataMap)
                .storeDurably()
                .build();
        return jobDetail;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean deleteJobDetail(String taskId) {
        try {
            scheduler.deleteJob(JobKey.jobKey(taskId, CommonString.TASK_GROUP_NAME));
        } catch (SchedulerException e) {
            log.info("任务删除失败");
        }
        return true;
    }

    @Override
    public JobDetail selectJobDetail(String taskId) {
        return null;
    }

    @Override
    public List<JobDetail> listJobDetail() {
        return null;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean checkJobDetail(String taskId) {
        boolean exists = true;
        try {
            exists = scheduler.checkExists(JobKey.jobKey(taskId, CommonString.TASK_GROUP_NAME));
        } catch (SchedulerException e) {
            log.info("任务检查失败");
        }
        return exists;
    }
}
